import { defineStore } from 'pinia'
import api from '@/api/session'

export const useConversationStore = defineStore('conversation', {
  state: () => ({
    list: [],
    detail: null,
    messages: [],
    loading: false,
    pagination: {
      page: 1,
      pageSize: 20,
      total: 0
    },
    filters: {
      username: '',
      startTime: '',
      endTime: ''
    },
    stats: {
      userActivity: [],
      hotQuestions: []
    }
  }),

  actions: {
    // 获取对话列表
    async fetchList() {
      this.loading = true
      try {
        const res = await api.getList({
          ...this.filters,
          page: this.pagination.page,
          pageSize: this.pagination.pageSize
        })
        console.log('获取对话列表:', res);

        this.list = res.data.data.list
        this.pagination.total = res.data.data.total
      } catch (error) {
        console.error('获取对话列表失败:', error)
        throw error
      } finally {
        this.loading = false
      }
    },

    // 获取对话详情
    async fetchDetail(id) {
      this.loading = true
      try {
        const res = await api.getDetail(id)
        console.log('获取对话详情:', res);

        this.detail = res.data.conv_001.data.conversation
        this.messages = res.data.conv_001.data.messages
      } catch (error) {
        console.error('获取对话详情失败:', error)
        throw error
      } finally {
        this.loading = false
      }
    },

    // 获取统计数据
    async fetchStats(params) {
      try {
        const res = await api.getStats(params)
        console.log(res);

        this.stats.userActivity = res.data.data.userActivity
        this.stats.hotQuestions = res.data.data.hotQuestions
      } catch (error) {
        console.error('获取统计数据失败:', error)
        throw error
      }
    },

    // 更新筛选条件
    updateFilters(filters) {
      this.filters = {
        username: filters.username || '',
        startTime: filters.startTime || '',
        endTime: filters.endTime || ''
      }
      this.pagination.page = 1
      this.fetchList()
    },

    // 分页变化
    changePage(page) {
      this.pagination.page = page
      this.fetchList()
    }
  }
})